package com.example.freeengine.wallpaper.fragment.everydayrefresh;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.freeengine.R;
import com.example.freeengine.databinding.FragmentWallPaperEveryDayRefreshBinding;
import com.example.freeengine.wallpaper.alarm.MyAlarmWorker;
import com.example.freeengine.wallpaper.constants.WallPaperConstant;
import com.example.freeengine.wallpaper.constants.WallPaperUpdateStrategy;
import com.example.freeengine.wallpaper.fragment.WallPaperViewModel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Terry Deng
 */
public class WallPaperEveryDayRefreshFragment extends Fragment {

    private static final String TAG = WallPaperEveryDayRefreshFragment.class.getSimpleName();
    FragmentWallPaperEveryDayRefreshBinding viewBinding;
    WallPaperViewModel wallPaperViewModel;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        viewBinding = FragmentWallPaperEveryDayRefreshBinding.inflate(inflater);
        return viewBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        wallPaperViewModel = new ViewModelProvider(requireActivity()).get(WallPaperViewModel.class);

        viewBinding.ivWallpaperEverydayrefreshPictureSource.setOnClickListener(v -> {
            PopupMenu popup = new PopupMenu(requireContext(), v);
            MenuInflater inflater = popup.getMenuInflater();
            inflater.inflate(R.menu.menu_wallpaper_everydayrefresh_picture_source_item, popup.getMenu());
            popup.show();

            popup.setOnMenuItemClickListener(item -> {

                switch (item.getItemId()){
                    case R.id.wallpaper_everydayrefresh_picture_resource_item_history: {
                        NavController navController = Navigation.findNavController(v);
                        Bundle bundle = new Bundle();
                        bundle.putString("path", requireContext().getFilesDir() + WallPaperConstant.WALLPAPER_EVERYDATREFRESH_BING_HISTORY_FILE_PATH);
                        navController.navigate(R.id.action_wallPaperEveryDayRefreshFragment_to_wallPaperEveryDayRefreshHistoryFragment, bundle);
                        return true;
                    }
                    case R.id.wallpaper_everydayrefresh_picture_resource_item_url: {

                        new AlertDialog.Builder(requireContext())
                                .setTitle("提示")
                                .setMessage("更新时间：" + wallPaperViewModel.getWallPaperAlarmWakeupTime(requireContext()) + "\n" + "url: " + wallPaperViewModel.getWallPaperEveryDayRefreshCurrentFlag(requireContext()))
                                .show();

                        return true;
                    }
                    case R.id.wallpaper_everydayrefresh_picture_resource_item_sysstatus: {

                        requireActivity().runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        Runtime mRuntime = Runtime.getRuntime();
                                        Process mProcess = null;
                                        try {
                                            String cmd = "dumpsys alarm | grep freeengine";
                                            mProcess = mRuntime.exec(cmd);
                                            try(BufferedReader mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream()))) {
                                                //Process中封装了返回的结果和执行错误的结果
                                                StringBuilder mRespBuff = new StringBuilder();
                                                char[] buff = new char[1024];
                                                int ch = 0;
                                                while ((ch = mReader.read(buff)) > 0) {
                                                    mRespBuff.append(buff, 0, ch);
                                                }
                                                System.out.print(mRespBuff.toString());
                                                new AlertDialog.Builder(requireContext())
                                                        .setTitle("提示")
                                                        .setMessage(mRespBuff.toString())
                                                        .show();

                                                mProcess.destroy();

                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                        );
                        return true;
                    }
                    default:
                        return false;
                }
            });
        });


        // 提前请求最新图片
        wallPaperViewModel.saveEverydayRefreshPicture(requireContext(), requireContext().getFilesDir() + WallPaperConstant.WALLPAPER_EVERYDATREFRESH_BING_HISTORY_FILE_PATH);
        viewBinding.btnWallpaperEverydayrefreshPictureSourceSet.setOnClickListener(v -> {
            if (viewBinding.btnWallpaperEverydayrefreshPictureSourceSet.isChecked()){
                new AlertDialog.Builder(requireContext())
                        .setTitle("提示")
                        .setMessage("是否确定将壁纸设置为每日更新?")
                        .setPositiveButton("确定", (dialog, which) -> {
                            wallPaperViewModel.setWallPaperUpdateStrategyInfo(WallPaperUpdateStrategy.FROM_EVERYDAY,
                                    requireContext(), "Bing");
                            new MyAlarmWorker.Builder(requireContext()).startEveryDayRefreshAlarm();
                        })
                        .setNegativeButton("取消", (dialog, which) -> viewBinding.btnWallpaperEverydayrefreshPictureSourceSet.toggle())
                        .setCancelable(false)
                        .show();
            }else {
                new AlertDialog.Builder(requireContext())
                        .setTitle("提示")
                        .setMessage("是否取消壁纸每日更新?")
                        .setPositiveButton("确定", (dialog, which) -> {
                            wallPaperViewModel.setWallPaperUpdateStrategyInfo(WallPaperUpdateStrategy.NOT_SET,
                                    requireContext(), "");
                            new MyAlarmWorker.Builder(requireContext()).stopAlarm();
                        })
                        .setNegativeButton("取消", (dialog, which) -> viewBinding.btnWallpaperEverydayrefreshPictureSourceSet.toggle())
                        .setCancelable(false)
                        .show();
            }
        });

        String wallPaperUpdateStrategyInfo = wallPaperViewModel.getWallPaperUpdateStrategyInfo(requireContext());
        if (wallPaperUpdateStrategyInfo.equals(WallPaperUpdateStrategy.FROM_EVERYDAY.name())){
            viewBinding.btnWallpaperEverydayrefreshPictureSourceSet.setChecked(true);
        }

    }
}